/*
 * debug.c
 *
 *  Created on: 2012. 4. 13.
 *      Author: jphong
 */

/* Debug level
 * 		raise the debugLevel, porduce less messages.
 */
#include	<stdio.h>
#include	<stdlib.h>
#include	<stdarg.h>		/* ANSI C header file */
#include	<string.h>

static int debugLevel = 1;
static void debout(const char *, va_list);

void setDebug(int level) {
	debugLevel = level;
}

/*
 * 	Print message if debugLevel set
 */
void debug(const char *fmt, ...) {
	va_list ap;

	if (debugLevel) {
		va_start(ap, fmt);
		debout(fmt, ap);
		va_end(ap);
	}
	return;
}

/* Print message if message level >= debugLevel
 * 		- Give higher level for more important message
 * 		- always print message if level = 0
 */
void debugl(int level, const char *fmt, ...) {
	va_list ap;

	if (debugLevel <= level) {
		va_start(ap, fmt);
		debout(fmt, ap);
		va_end(ap);
	}
	return;
}

static void debout(const char *fmt, va_list ap) {
	char buf[4096];

	vsprintf(buf, fmt, ap);

	fflush(stdout); /* in case stdout and stderr are the same */
	fputs(buf, stderr);
	fflush(stderr);

	return;
}
